package sort;

/**
 *  归并排序, 后续遍历二叉树
 *  https://blog.csdn.net/qq_44171009/article/details/116119293
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] source = {11, 44, 23, 67, 88, 65, 34, 48, 9, 12, 13};
        int[] tmp = new int[source.length];    //新建一个临时数组存放
        mergeSort(source, 0, source.length - 1, tmp);
        for (int i = 0; i < source.length; i++) {
            System.out.print(source[i] + " ");
        }
    }

    public static void merge(int[] source, int low, int mid, int high, int[] temp) {
        //临时数组索引位置
        int i = 0;
        //左边序列和右边序列起始索引
        int j = low, k = mid + 1;
        //左边有序的和右边有序的，按位对比,合并到 temp 中
        while (j <= mid && k <= high) {
            if (source[j] < source[k]) {
                temp[i++] = source[j++];
            } else {
                temp[i++] = source[k++];
            }
        }
        //若左边序列还有剩余，则将其全部拷贝进 tmp[] 中
        while (j <= mid) {
            temp[i++] = source[j++];
        }
        //若右边边序列还有剩余，则将其全部拷贝进 tmp[] 中
        while (k <= high) {
            temp[i++] = source[k++];
        }
        // 整理好的temp有序数据覆盖到source
        for (int t = 0; t < i; t++) {
            source[low + t] = temp[t];
        }
    }

    /**
     * 后续遍历二叉树
     */
    public static void mergeSort(int[] arr, int low, int high, int[] tmp) {
        if (low < high) {
            int mid = (low + high) / 2;
            mergeSort(arr, low, mid, tmp); //递归左边
            mergeSort(arr, mid + 1, high, tmp);  //递归左边
            merge(arr, low, mid, high, tmp);    //合并两个有序序列
        }
    }


}
